import axios from 'axios'

const service = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 5000,
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = uni.getStorageSync('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error(error)
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      uni.showToast({
        title: response.data.message || '请求失败',
        icon: 'none',
      })
      return Promise.reject(new Error(response.data.message || '请求失败'))
    }
    return response.data
  },
  (error) => {
    console.error(error)
    uni.showToast({
      title: error.message || '请求失败',
      icon: 'none',
    })
    return Promise.reject(error)
  },
)

export default service
